const express = require('express')
const { readJsonAsObject, writeObjectAsJson } = require('./util')


const app = express()

app.use(express.json())
app.use(express.urlencoded({ extended: false }))


const DATA_FILE = 'data.json'


try {
    var obj = readJsonAsObject(DATA_FILE)
}
catch (e) {
    var obj = {
        "id_next": 1,
        "list": [   
        ]
    }
    writeObjectAsJson(DATA_FILE, obj)
}


app.post('/add', function(req, res) {
    var new_task = {
        "id": obj.id_next,
        "title": "作业",
        "add_time": Date.now(),
        "stop_time": req.body.stop_time,
        "is_finish": false
    }
    obj.list.push(new_task)
    obj.id_next += 1
    writeObjectAsJson(DATA_FILE, obj)
    res.send(new_task)
})


app.post('/all', function(req, res) {
    res.send({
        "list": obj.list
    })
})


app.post('/profile',(req,res)=>{
    obj = readJsonAsObject('./data.json')
    var checkId = 2
    if(obj.list.length<checkId){
        console.log("error");
        res.send("error")
    }
    else{
    obj.list.forEach(element => {
        if(element.id === checkId){
            console.log(element);
            res.send(element)
            
        }

    });
}
})
app.post('/update',(req,res)=>{
    obj = readJsonAsObject('./data.json')
    var checkId2 = 2
    var mod={
        "id": checkId2,
        "title": "考试",
        "add_time": 114514,
        "stop_time": req.body.stop_time,
        "is_finish": false
    }
    obj.list.forEach(element => {
        if(element.id === checkId2){
            obj.list.splice(checkId2-1,1,mod)
            console.log(obj);
            writeObjectAsJson(DATA_FILE, obj)
            
        }
    });
})

app.post('/delete',(req,res)=>{
    var deleteId = 3
    obj = readJsonAsObject('./data.json')
    if(obj.list.length<deleteId)
        {
            console.log("error");
            res.send("error")
        }
    else
    {
        obj.list.forEach(element => {
        if(element.id === deleteId){
            obj.list.splice(deleteId-1,1)
            
            obj.list.forEach((element,index)=>{
                element.id=index+1
            })
            obj.id_next=obj.list.length+1
            console.log(obj)
            writeObjectAsJson(DATA_FILE, obj)
            
        }
    });
    }

})

app.listen(3000, '0.0.0.0', function() {
    console.log("Server start at http://127.0.0.1:3000")
})